import * as React from 'react';
import { connect } from 'react-redux';
import { message, Icon } from 'antd';
import { fetchKnowledgeDetail } from 'actions/knowledge';

import LoadableComponent from 'components/common/LoadableComponent';
const LoadablePopKnowledgeSelect = LoadableComponent(() => import('pages/knowledge/PopToSelect'));
const LoadableMedia = LoadableComponent(() => import('components/common/Media'));

interface EditKnowledgeProps {
  dispatch: (action: any) => any;
  handleUpdateKnowledge: (id: number) => any;
  loading: boolean;
  showImage: boolean;
  knowledgeId: number;
  selectNumber?: number;
  lessonId?: number;
}

interface EditKnowledgeState {
  isSelectKnowledge: boolean;
  knowledgeDetail: any;
}

class EditKnowledge extends React.Component<EditKnowledgeProps, EditKnowledgeState> {
  static defaultProps: EditKnowledgeProps = {
    dispatch: () => {},
    handleUpdateKnowledge: () => {},
    loading: false,
    showImage: true,
    knowledgeId: 0,
    selectNumber: 1,
    lessonId: 0,
  };
  constructor(props: EditKnowledgeProps) {
    super(props);
    this.state = {
      isSelectKnowledge: false,
      knowledgeDetail: null,
    };
  }

  componentWillMount() {
    if (this.props.knowledgeId) {
      this.handleFetchKnowledgeDetail(this.props.knowledgeId);
    }
  }

  componentWillReceiveProps(nextProps: any) {
    const { knowledgeId } = nextProps;
    const { knowledgeId: oldKnowledgeId } = this.props;
    if (knowledgeId !== oldKnowledgeId) {
      if (knowledgeId !== 0) {
        this.handleFetchKnowledgeDetail(knowledgeId);
      } else {
        this.setState({
          knowledgeDetail: null,
        });
      }
    }
  }

  handleFetchKnowledgeDetail = (knowledgeId: number) => {
    this.props.dispatch(fetchKnowledgeDetail(knowledgeId)).then((result: any) => {
      if (result.code) {
        message.error(result.msg);
      } else {
        this.setState({
          knowledgeDetail: result.response.data,
        });
      }
    });
  };

  handleOpenModal = () => {
    this.setState({
      isSelectKnowledge: true,
    });
  };

  handleCloseModal = () => {
    this.setState({
      isSelectKnowledge: false,
    });
  };

  handleRemoveKnowledge = () => {
    this.props.handleUpdateKnowledge(0);
  };

  renderItems() {
    const { knowledgeDetail } = this.state;
    const { selectNumber, showImage } = this.props;

    let renderHtml = null;
    if (knowledgeDetail) {
      renderHtml = (
        <div className="item-knowledge" style={{ position: 'relative' }}>
          {showImage ? (
            <LoadableMedia
              attachment={knowledgeDetail.images[0]}
              onDestroy={this.handleRemoveKnowledge}
              imageStyle={{ width: '50%' }}
            />
          ) : (
            <>
              <LoadableMedia
                attachment={knowledgeDetail.audio}
                onDestroy={this.handleRemoveKnowledge}
              />
              {selectNumber && selectNumber > 1 && <span>X {selectNumber}</span>}
            </>
          )}
        </div>
      );
    } else {
      renderHtml = (
        <p className="loading-placeholder">
          还没有数据，&nbsp;
          <a href="javascript:void(0);" onClick={this.handleOpenModal}>
            <Icon type="plus" />
            添加
          </a>
        </p>
      );
    }

    return <div className="custom-tags no-click">{renderHtml}</div>;
  }

  handleSubmit = (ids: number[]) => {
    this.props.handleUpdateKnowledge(ids[0]);
    this.handleCloseModal();
  };

  render() {
    const { isSelectKnowledge, knowledgeDetail } = this.state;
    const { lessonId } = this.props;
    let ownItems = [];
    if (knowledgeDetail) {
      ownItems.push(knowledgeDetail);
    }

    return (
      <div>
        {isSelectKnowledge && (
          <LoadablePopKnowledgeSelect
            selectMax={1}
            lessonId={lessonId}
            ownItems={ownItems}
            handleSubmitCallback={this.handleSubmit}
            onClose={this.handleCloseModal}
          />
        )}
        <div>
          <h4 className="text-left test-parser-sub-title">知识点</h4>
          {this.renderItems()}
        </div>
      </div>
    );
  }
}

interface OwnProps {
  handleUpdateKnowledge: (id: number) => any;
  showImage: boolean;
  knowledgeId: number;
}

function mapStateToProps(state: any, ownProps: OwnProps) {
  const { loading } = state.knowledge;
  const { handleUpdateKnowledge, showImage, knowledgeId } = ownProps;

  return {
    loading,
    showImage,
    knowledgeId,
    handleUpdateKnowledge,
  };
}

export default connect(mapStateToProps)(EditKnowledge);
